from django.shortcuts import render

from django.http import HttpResponse,JsonResponse

from .. models import Goods,Types

from . typesviews import GetTypesAll
from . userviews import uploads

import os
# Create your views here.

# def index(request):
#     return render(request,'myadmin/goods/index.html')
def index(request):


    # 获取所有的商品
    obs = Goods.objects.filter()
    # 搜索条件
    if request.GET.get('type',None):
        obs = obs.filter(title__contains = request.GET['keywords'])

    # 数据分页
    # 获取当前页的页数
    pageindex = request.GET.get('p',1)
    # 导入分页类
    from django.core.paginator import Paginator
    # 实例化分页对象
    p = Paginator(obs, 2)

    # 获取当前页的 数据
    goodslist = p.page(pageindex)

    # 分配数据
    context = {'goodslist':goodslist}

    # 加载模板
    return render(request,'myadmin/goods/index.html',context)

 
def add(request):

    context = {'typelist': GetTypesAll(request)}
    return render(request,'myadmin/goods/add.html',context)


def insert(request):
    # 这里不是edit，不需要再查询一遍放到页面中
    data = request.POST.dict()

    del data['csrfmiddlewaretoken']

    # 判断是否由文件上传
    myfile = request.FILES.get('pic',None)
    if myfile:
        # 上传图片 uploads
        data['pic'] = uploads(myfile)
    else:
        # 商品是必须要给图的，否则对客户没有吸引力，也可以有效防止假货;如果有假货，外观明显不一致就可以作为证据
        return HttpResponse('<script>alert("必须上传图片");history.back(-1);<script>')


    # 数据齐全后，就可以将data中的数据添加到数据库,但是外键tid的数据类型必须先改为obj
    data['tid'] = Types.objects.get(id = data['tid'])
    res = Goods.objects.create(**data)

    if res:
        return HttpResponse('<script>alert("添加成功");location.href="/myadmin/goods/index/"</script>')
    else:
        return HttpResponse('<script>alert("添加失败");history.back(-1);</script>')


# 执行商品删除
def delete(request):
    if request.is_ajax():
        try:
            # 获取id,执行逻辑删除
            id=request.GET.get('id',None)
            ob = Goods.objects.get(id=id)
            # ob.isDelete = True
            # ob.save()
            if ob.pic:
            # /static/pics/
                os.remove('.'+ob.pic)

            ob.delete()

            return JsonResponse({'code':1,'msg':'删除成功'})
        except:
            return JsonResponse({'code':0,'msg':'删除失败'})
    else:
        # 返回一个404的错误页面
        return HttpResponse("Poll does not exist")

# 商品编辑
def edit(request,gid):
    # 获取商品信息
    goods = Goods.objects.get(id=gid)
    
    # 分配数据
    context = {'goods':goods,'typelist':GetTypesAll(request)}

    # 加载模板
    return render(request,'myadmin/goods/edit.html',context)


def update(request):

    # 获取数据 ==request.POST.copy.dict(),允许省略copy
    data = request.POST.dict()
    del data['csrfmiddlewaretoken']

    print(data)
    # 获取原有的商品数据，更新什么，就改什么，注意：仅有一部分数据是在add或edit页面中添加的，所以 data = request.POST.dict() 获取的数据并不完整
    ob = Goods.objects.get(id = data['id'])

    ob.title = data['title']
    ob.price = data['price']
    ob.store = data['store']
    ob.info = data['info']

    # 判断是否更新了图像，图像不是以http协议request的post或get提交的，而是FILES协议
    myfile = request.FILES.get('pic',None)
    if myfile:
        # 必须删除原来的图像，图片不能重名，要么就用random,和一对多关系，将多个同样内容但是不同名字的图片关联起来     
        # 删除原来的图片,这里没有给商品设置默认图片
        if ob.pic:
            try:
                os.remove(BASE_DIR + ob.pic)
            except:
                pass
        ob.pic = uploads(myfile)

    ob.save()

    return HttpResponse('<script>alert("更新成功");location.href="/myadmin/goods/index/"</script>')


